package org.example.java.util.concurrency.catch_exception;

import java.util.concurrent.*;

/**
 * Created by Juntao.Zhang on 2014/10/25.
 * 简单线程
 * 通过get异常捕获
 */
public class SimpleGetCatchException {
  public static void main(String[] args) throws InterruptedException {
    ExecutorService es = Executors.newFixedThreadPool(2);
    ExecutorCompletionService<String> ecs = new ExecutorCompletionService<>(es);
    //上述代码只有在调用get()时抛出异常，否则不打印任何异常信息
    Future future = ecs.submit(new Runnable() {
      int count = 0;
      boolean flag = true;

      @Override
      public void run() {
        while (flag) {
          count++;
          System.out.println("run finish");
          try {
            TimeUnit.SECONDS.sleep(1);
            if (count == 5) {
//              flag = false;
              throw new RuntimeException("my simple get test");
            }
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }, "success");

    try {
//      System.out.println(ecs.take().get());
      System.out.println(future.get());
      System.out.println("exit");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      es.shutdown();
    }
  }
}
